IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'EAI_InsertUpdateReimOverseaItems')
	BEGIN
		DROP  Procedure  EAI_InsertUpdateReimOverseaItems
	END

GO

CREATE procedure [dbo].[EAI_InsertUpdateReimOverseaItems]
(
	@CompanyCode varchar(20),
	@DocumentID varchar(50),
	@ItemID uniqueidentifier,
	@ReimOverseaLinkKey varchar(50),
	@ExpenseItemName varchar(50),
	@Country varchar(10),
	@Sum money,
	@Currency varchar(10),
	@AccountingLedge nvarchar(50),
	@lastOperateDate datetime
)
as 
	declare @ReimOverseaItemID uniqueidentifier
	declare @ReimOverseasID uniqueidentifier
	
	declare @Status int
	declare @ImportIntoSAPDate datetime
	declare @CostCenter varchar(50)

	set @ReimOverseaItemID=null
	set @ReimOverseasID=null

	select @ReimOverseaItemID=ItemID from ReimOverseasItems where SerialNumber=@DocumentID

	select @ReimOverseasID=ReimOverseasID,@Status=Status,@ImportIntoSAPDate=ImportIntoSAPDate,@CostCenter=CostCenter
	from ReimOverseas where ReimOverseaLinkKey=@ReimOverseaLinkKey and CompanyCode=@CompanyCode
	
	if @ReimOverseasID is not null
	begin
		if @ReimOverseaItemID is null
		begin
			insert into ReimOverseasItems(ItemID,ReimOverseasID,SerialNumber,AccountingLedge,CostCenter,Currency,SubTotal,ImportIntoSAPDate,Status,ReimOverseaLinkKey)
			values(newid(),@ReimOverseasID,@DocumentID,@AccountingLedge,@CostCenter,@Currency,@Sum,@ImportIntoSAPDate,@Status,@ReimOverseaLinkKey)
		end
		else
		begin
			update ReimOverseasItems
			set AccountingLedge=@AccountingLedge,
				CostCenter=@CostCenter,
				ImportIntoSAPDate=@ImportIntoSAPDate,
				Status=@Status,
				ReimOverseasID=@ReimOverseasID,
				Currency=@Currency,
				SubTotal=@Sum
			where ItemID=@ReimOverseaItemID		
		end
	end
go
